function q_sd_solve = q_sd_calib_fn(q_sd_guess,inputs_struc,fns_struc)

% This function basically just calls another function with an fsolve to
% calibrate the std dev of productivity distribution and the extent of
% non-homotheticity Delta

% Function handle which gets inputed into the fsolve.
q_sd_zero_handle = @(q_sd)q_sd_zero(q_sd,inputs_struc,fns_struc);

% Solves for the a_q's which match the share of employment in each q.
options_q = optimset('Display','iter');
q_sd_solve = fsolve(q_sd_zero_handle,q_sd_guess,options_q);
  

end

function error_q_sd = q_sd_zero(q_sd,inputs_struc,fns_struc)

non_equi_space = inputs_struc.non_equi_space; min_q = inputs_struc.min_q;
no_q = inputs_struc.no_q; log_base = inputs_struc.log_base;
price_income_slope_target = inputs_struc.price_income_slope_target;
prod_grid_size = inputs_struc.prod_grid_size; w_U = inputs_struc.w_U;
std_dev_target = inputs_struc.std_dev_target;
sd_entrant = inputs_struc.sd_entrant;

max_q = q_sd(1);

q_guess = linspace(min_q,max_q,no_q)';
if non_equi_space==1
    q_guess =log(linspace(log_base^(min_q),log_base^(max_q),no_q))'./log(log_base);
end
inputs_struc.q = q_guess;

% Returns calibrated vlues of a_q which match the share of employment in
% different q's for the given Delta.
a_q = a_q_calib_fn(inputs_struc,fns_struc);
inputs_struc.a_q = [0;a_q];

Output_struc = solve_equi(inputs_struc,fns_struc);

w_S_calib=Output_struc.w_S ; p_q_i_calib=Output_struc.p_q_i;
rho_q_U_calib=Output_struc.rho_q_U;rho_q_S_calib=Output_struc.rho_q_S; 
d_q_i_calib=Output_struc.d_q_i; 
l_U_q_i_calib=Output_struc.l_U_q_i; l_S_q_i_calib=Output_struc.l_S_q_i;
M_q_calib = Output_struc.M_q;

% Slope assuming that there is no final quality producer in the middle
% but just the fact that the consumers purchase the intermediates
% directly. The slope is exactly the same if I weight each price by
% expenditure share of that intermediate which makes sense as the CES
% price index also weights the same way!
exp_wt = d_q_i_calib.*p_q_i_calib./repmat(sum(d_q_i_calib.*p_q_i_calib,2),1,prod_grid_size);
slope_exp_wt = (sum(sum(repmat(rho_q_S_calib,1,prod_grid_size).*log(p_q_i_calib).*exp_wt)) - sum(sum(repmat(rho_q_U_calib,1,prod_grid_size).*log(p_q_i_calib).*exp_wt)))/(log(w_S_calib) - log(w_U));
    
error_max_q = slope_exp_wt/price_income_slope_target - 1;

error_q_sd = [error_max_q];

end
